﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;

namespace Kokomo.Environment.Hosting.Services
{
	public class EditorManager : NotifierObject
	{
		public EditorManager()
		{
			this._editors = new List<DocumentEditor>();
		}

		private List<DocumentEditor> _editors;
		public void RegisterEditor(DocumentEditor editor)
		{
			if (editor == null) throw new ArgumentNullException("editor");

			this._editors.Add(editor);
		}

		public DocumentEditor[] GetEditors()
		{
			return this._editors.ToArray();
		}

		public IEnumerable<FileType> GetSupportedFileTypes()
		{
			List<FileType> fileTypes = new List<FileType>();
			foreach (var editor in this._editors)
			{
				IEnumerable<FileType> editorFileTypes = editor.SupportedFileTypes;
				foreach (var editorFileType in editorFileTypes)
				{
					fileTypes.Add(editorFileType);
				}
			}

			return fileTypes;
		}

		public DocumentEditor SuggestEditor(string path)
		{
			if (path == null) throw new ArgumentNullException("path");

			DocumentEditor matchEditor = null;
			foreach (var editor in this._editors)
			{
				IEnumerable<FileType> editorFileTypes = editor.SupportedFileTypes;
				if (editorFileTypes != null)
				{
					foreach (var editorFileType in editorFileTypes)
					{
						if (editorFileType.Matches(path))
						{
							matchEditor = editor;
							return matchEditor;
						}
					}
				}
			}

			if (matchEditor != null)
			{
				FileType fileType = FileTypeFilter.DetermineFileType(path, this._editors.SelectMany(e => e.Filters));
				if (fileType != null)
				{
					matchEditor = this._editors.FirstOrDefault(e => e.SupportedFileTypes.Contains(fileType));
				}
			}

			return matchEditor;
		}
	}
}
